import { ref } from "vue";
import { defineStore } from "pinia";
import { http } from "@/utils/http";
import { useLocationParams } from "@/store/useLocationStore";
import { useCourseData } from "@/store/useCourse";
import { sendPullState as sendPullStateLive } from "@/views/LiveNew/LiveNewApi";

export const useQuestionnaireStore = defineStore("questionnaire", () => {
  const { getParam, getAllParams } = useLocationParams();
  const questionnaireInfo = ref<any>();
  const roomParams = ref<any>({});
  const scene = ref("1");
  const space = ref("/live");

  const totalAttempts = ref(0); // 剩余答题次数
  const usedAttempts = ref(0); // 已答题次数

  const getRoomWatchRecordByUserId = async params => {
    scene.value = params.scene;
    space.value = params.scene == "2" ? "/live" : "/screening";
    const data = {
      inviteCode: getParam("inviteCode"),
      scene: params.scene,
      roomId: params.rId,
      userId: params.buyId,
      shopId: params.spId,
      subjectId: params.sId,
      liveInfoId: params.sId,
      subjectRecordsId: params.srId
    };
    const res = await http.request<any>({
      method: "POST",
      url: `${space.value}/getRoomWatchRecordByUserId`,
      data
    });

    const detail = params.scene == "2" ? res.liveVo : res.subjectVo;
    questionnaireInfo.value = detail;
    roomParams.value = {
      ...data,
      ...res,
      subjectVo: undefined,
      liveVo: undefined,
      watchType:
        params.scene == "2"
          ? detail?.openType == 0
            ? "REAL_TIME"
            : "PLAY_BACK"
          : undefined
    };

    totalAttempts.value = +detail?.answerNum;
    usedAttempts.value = res.answerNum ?? 0;
    console.log("totalAttempts.value", totalAttempts.value);
    console.log("usedAttempts.value", usedAttempts.value);
    console.log("roomParams.value", roomParams.value);

    return {
      ...roomParams.value,
      shopName: detail.shopName,
      questionSettingVoList: detail.questionSettingVoList ?? []
    };
  };

  const checkRoomWatchRecordResult = async params => {
    const res = await getRoomWatchRecordByUserId(params);
    if (res?.result) {
      return {
        name: "Questionnaire",
        query: { ...getAllParams() }
      };
    } else {
      return false;
    }
  };

  const postAnswerCompensation = async (answerState: number) => {
    const res = await http.request<{ amount: number; rewardType?: number }>({
      url: `${space.value}/answerCompensation`,
      method: "POST",
      data: {
        ...roomParams.value,
        // 答题状态，1：答题正确、2：答题失败
        answerState
      }
    });

    roomParams.value.amount = res?.amount;
    roomParams.value.rewardType = res?.rewardType;

    return res;
  };

  const recordAnswerAttempt = async () => {
    const res = await http.request<number>({
      url: `${space.value}/record-answer`,
      headers: { application: "json" },
      method: "POST",
      data: {
        ...roomParams.value
      }
    });

    usedAttempts.value = res;

    return res;

    // usedAttempts.value += 1;
  };

  const postRewardCompensation = () => {
    return http.request<any>({
      url: `${space.value}/rewardCompensation`,
      method: "POST",
      data: { ...roomParams.value }
    });
  };

  const sendPullState = (pullState: number, sn: string) => {
    if (scene.value == "2") {
      sendPullStateLive(pullState, sn);
    } else {
      useCourseData().sendPullState(pullState, sn);
    }
  };

  return {
    roomParams,
    totalAttempts,
    usedAttempts,
    questionnaireInfo,
    checkRoomWatchRecordResult,
    getRoomWatchRecordByUserId,
    postAnswerCompensation,
    postRewardCompensation,
    recordAnswerAttempt,
    // getRoomWatchData,
    sendPullState
  };
});
